package com.jf.docsify.servlet.git;

import io.undertow.security.idm.Account;
import io.undertow.security.idm.Credential;
import io.undertow.security.idm.IdentityManager;
import io.undertow.security.idm.PasswordCredential;

import java.io.Serializable;
import java.security.Principal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;

import com.jf.docsify.common.utils.JdbcUtil;
import com.jf.docsify.common.utils.SecurityUtil;
import com.jf.docsify.modules.model.SysUser;
import com.jfinal.kit.HashKit;
import com.sun.net.httpserver.HttpPrincipal;

/**
 * Description:
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/29.1       chenwr    2022/7/29           Create
 * </pre>
 * @date 2022/7/29
 */
public class GitIdentityManager implements IdentityManager, Serializable {

    private static final long serialVersionUID = -5560990435902689329L;

    @Override
    public Account verify(Account account) {
        return account;
    }

    /**
     * 验证用户名密码
     * @param userName
     * @param credential
     * @return
     */
    @Override
    public Account verify(String userName, Credential credential) {
        PasswordCredential passwordCredential = (PasswordCredential) credential;
        char[] passwordChar = passwordCredential.getPassword();
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < passwordChar.length; i++) {
            password.append(passwordChar[i]);
        }
        String secMd5Pwd = SecurityUtil.md5(HashKit.md5(password.toString()));
        List<SysUser> sysUsers = JdbcUtil.executeQuery("select * from sys_user where user_name = ? and (password = ? or password = ?)", SysUser.class, userName, secMd5Pwd, password.toString());
        if (CollectionUtils.isEmpty(sysUsers)) {
            return null;
        }
        return new Account() {
            @Override
            public Principal getPrincipal() {
                return new HttpPrincipal(userName, "jf-docsify");
            }

            @Override
            public Set<String> getRoles() {
                Set<String> roles = new HashSet<>();
                roles.add("all");
                return roles;
            }
        };
    }

    @Override
    public Account verify(Credential credential) {
        return null;
    }
}